﻿using System;
using System.Collections.Generic;
using System.Xml;
using DocumentBuilder.Controls.DataSources.Collection;

namespace DocumentBuilder.Controls.DataSources
{
    public class DataSourceFactory
    {
        private static readonly IDictionary<string, ControlDataSourceType> DataSourceTypes 
            = new Dictionary<string, ControlDataSourceType>
                  {
                      { "list", ControlDataSourceType.ObjectCollection },
                      { "table", ControlDataSourceType.DataTable },
                      { "xml", ControlDataSourceType.Xml },
                      { "text", ControlDataSourceType.Text },
                      { "scalar", ControlDataSourceType.Scalar },
                  };

        private DataSourceFactory()
        {
        }

        public static IDataSource Create(Document context, XmlNode dataSourceNode)
        {
            var type = DataSourceTypes["list"];
            var queryId = string.Empty;
            var of = string.Empty;
            var id = string.Empty;

            if (dataSourceNode.Attributes != null)
            {
                if (dataSourceNode.Attributes["type"] != null)
                    type = DataSourceTypes[dataSourceNode.Attributes["type"].Value];

                if (dataSourceNode.Attributes["usequery"] != null)
                    queryId = dataSourceNode.Attributes["usequery"].Value;

                if (dataSourceNode.Attributes["of"] != null)
                    of = dataSourceNode.Attributes["of"].Value;

                if (dataSourceNode.Attributes["id"] != null)
                    id = dataSourceNode.Attributes["id"].Value;
            }

            switch(type)
            {
                case ControlDataSourceType.ObjectCollection:
                    if (String.IsNullOrEmpty(queryId) || context.Queries[queryId] == null)
                        throw new Exception("Invalid query id for datasource to populate");

                    if (String.IsNullOrEmpty(of) || context.ViewObjects[of] == null)
                        throw new Exception(String.Format("Invalid viewObject to fill with query {0}", queryId));

                    if (String.IsNullOrEmpty(id))
                        throw new Exception("Id must be specified for repeater control");

                    return new ObjectCollection(id, context.Queries[queryId].Fill(context.ViewObjects[of]));
            }

            return null;
        }
    }
}
